"""Playwright调试脚本 - 分析淘宝页面结构"""

import asyncio
from playwright.async_api import async_playwright


async def debug_taobao_page():
    """调试淘宝页面结构"""
    async with async_playwright() as p:
        # 启动浏览器
        browser = await p.chromium.launch(
            headless=False,  # 显示浏览器
            args=[
                '--no-sandbox',
                '--disable-blink-features=AutomationControlled',
                '--disable-web-security',
                '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            ]
        )
        
        # 创建上下文和页面
        context = await browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        )
        
        page = await context.new_page()
        
        # 设置反检测
        await page.add_init_script("""
            Object.defineProperty(navigator, 'webdriver', {
                get: () => undefined,
            });
        """)
        
        try:
            print("1. 访问淘宝首页...")
            await page.goto('https://www.taobao.com', wait_until='domcontentloaded', timeout=30000)
            await asyncio.sleep(3)
            
            print("2. 访问搜索页面...")
            search_url = 'https://s.taobao.com/search?q=%E6%95%B0%E6%8D%AE%E7%BA%BF&s=0&sort=sale-desc'
            await page.goto(search_url, wait_until='networkidle', timeout=60000)
            await asyncio.sleep(10)
            
            # 尝试滚动页面触发内容加载
            print("   滚动页面触发内容加载...")
            await page.evaluate('window.scrollTo(0, document.body.scrollHeight/2)')
            await asyncio.sleep(3)
            await page.evaluate('window.scrollTo(0, 0)')
            await asyncio.sleep(3)
            
            print(f"3. 当前页面标题: {await page.title()}")
            print(f"4. 当前页面URL: {page.url}")
            
            # 检查页面内容
            print("\n5. 检查页面关键词...")
            content = await page.content()
            print(f"   页面内容长度: {len(content)} 字符")
            
            # 保存页面内容到文件以便分析
            with open('taobao_page_content.html', 'w', encoding='utf-8') as f:
                f.write(content)
            print("   页面内容已保存到 taobao_page_content.html")
            
            keywords = ['商品', '价格', '销量', '店铺', 'item', 'product', 'goods', '数据线', '¥']
            for keyword in keywords:
                if keyword in content:
                    print(f"   ✓ 找到关键词: {keyword}")
                else:
                    print(f"   ✗ 未找到关键词: {keyword}")
            
            # 检查是否有反爬或异常内容
            suspicious_keywords = ['验证码', 'captcha', '滑块', '机器人', 'robot', '异常', '访问被拒绝']
            for keyword in suspicious_keywords:
                if keyword in content:
                    print(f"   ⚠️  检测到可疑关键词: {keyword}")
            
            # 尝试不同的商品选择器
            print("\n6. 测试商品选择器...")
            selectors = [
                '.item',
                '.Card--doubleCardWrapper--L2XFE73',
                '[data-category="auctions"]',
                '.items .item',
                '.grid .item',
                '.m-itemlist .item',
                '.item.J_MouserOnverReq',
                '.item.J_MouseEnterLeave',
                '[data-spm="item"]',
                '.Card',
                '.Card--card',
                '.contentInner--contentInner--QVTcU0M',
                '.leftView--leftView--1kVdNon',
                '.rightView--rightView--1kVdNon',
                '.shopcard',
                '.product',
                '.goods-item',
                '.search-item',
                '.result-item'
            ]
            
            for selector in selectors:
                try:
                    elements = await page.query_selector_all(selector)
                    if elements:
                        print(f"   ✓ {selector}: 找到 {len(elements)} 个元素")
                        
                        # 获取第一个元素的HTML片段
                        if len(elements) > 0:
                            html = await elements[0].inner_html()
                            print(f"     第一个元素HTML长度: {len(html)} 字符")
                            if len(html) > 100:
                                print(f"     HTML片段: {html[:200]}...")
                    else:
                        print(f"   ✗ {selector}: 未找到元素")
                except Exception as e:
                    print(f"   ✗ {selector}: 错误 - {e}")
            
            # 检查是否有登录或验证码页面
            print("\n7. 检查特殊页面状态...")
            title = await page.title()
            url = page.url
            
            if '登录' in title or 'login' in url.lower():
                print("   ⚠️  检测到登录页面")
            elif '验证' in title or 'captcha' in url.lower():
                print("   ⚠️  检测到验证码页面")
            else:
                print("   ✓ 正常搜索页面")
            
            # 等待用户观察
            print("\n8. 浏览器将保持打开30秒供观察...")
            await asyncio.sleep(30)
            
        except Exception as e:
            print(f"调试过程中出错: {e}")
        
        finally:
            await browser.close()


if __name__ == "__main__":
    asyncio.run(debug_taobao_page())